package com.example.app.Websocket;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URI;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class DataWebSocketManager {
    private static final String TAG = "DataWebSocketManager";
    private WebSocketClient webSocket;
    private final String serverUrl;
    private DataMessageListener messageListener;

    public interface DataMessageListener {
        void onTextMessageReceived(String fromUser, String message);
        void onImageMessageReceived(String fromUser, String imageUrl);
        void onAudioMessageReceived(String fromUser, String audioUrl);
        void onFileMessageReceived(String fromUser, String fileUrl);
        void onConnectionStatusChanged(boolean isConnected);

        void onImageReceived(String fromUser, byte[] imageData);
    }
    public void sendBinaryMessage(byte[] data) {
        System.out.println("websocket是否处于连接状态"+webSocket.isOpen());
        if (webSocket != null && webSocket.isOpen()) {
            System.out.println("发送逻辑执行成功");
            webSocket.send(data);
        }
    }
    public DataWebSocketManager(String serverUrl) {
        this.serverUrl = serverUrl;
    }
    public void setMessageListener(DataMessageListener listener) {
        this.messageListener = listener;
    }
    private void handleBinaryMessage(ByteBuffer bytes) {
        try {
            ByteBuffer copy = bytes.duplicate();
            int metaLength = copy.getInt();

            byte[] metaBytes = new byte[metaLength];
            copy.get(metaBytes);
            JSONObject metadata = new JSONObject(new String(metaBytes));

            byte[] imageData = new byte[copy.remaining()];
            copy.get(imageData);

            if (messageListener != null) {
                messageListener.onImageReceived(
                        metadata.getString("from"),
                        imageData
                );
            }
        } catch (Exception e) {
            Log.e(TAG, "二进制消息解析失败", e);
        }
    }

    public void  connect(String username) {
        try {
            SSLContext sslContext = createInsecureSSLContext();
            URI uri = new URI(serverUrl + "?username=" + username);
            webSocket = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    Log.d(TAG, "Data WebSocket connected");
                    if (messageListener != null) {
                        messageListener.onConnectionStatusChanged(true);
                    }
                }
                @Override
                public void onMessage(String message) {
                    handleIncomingMessage(message);
                }
                @Override
                public void onMessage(ByteBuffer bytes) {
                    handleBinaryMessage(bytes);
                }
                public void reconnect() {
                    new Handler(Looper.getMainLooper()).postDelayed(() -> {
                        if (webSocket != null && !webSocket.isOpen()) {
                            connect(); // 重新连接
                        }
                    }, 3000); // 3秒后重试
                }
                @Override
                public void onClose(int code, String reason, boolean remote) {
                    if (username!=""){
                        reconnect();
                    }
                    Log.d(TAG, "Data WebSocket closed");
                    if (messageListener != null) {
                        messageListener.onConnectionStatusChanged(false);
                    }
                }
                @Override
                public void onError(Exception ex) {
                    Log.e(TAG, "Data WebSocket error: " + ex.getMessage());
                }
            };
            webSocket.setSocketFactory(sslContext.getSocketFactory());
            webSocket.connect();
        } catch (Exception e) {
            Log.e(TAG, "Data WebSocket connection error: " + e.getMessage());
        }
    }

    private void handleIncomingMessage(String message) {
        try {
            JSONObject json = new JSONObject(message);
            String type = json.getString("type");
            String fromUser = json.getString("from");
            String content = json.getString("content");
            System.out.println(json);

            switch (type) {
                case "text":
                    if (messageListener != null) {
                        messageListener.onTextMessageReceived(fromUser, content);
                    }
                    break;
                case "image":
                    messageListener.onImageMessageReceived(fromUser, content);
                    break;
                case "audio":
                    messageListener.onAudioMessageReceived(fromUser, content);
                    break;
                case "file":
                    messageListener.onFileMessageReceived(fromUser, content);
                    break;
            }
        } catch (JSONException e) {
            Log.e(TAG, "Message parse error: " + e.getMessage());
        }
    }

    public void sendTextMessage(String  From,String toUser, String message) {
        sendMessage(From, toUser,"text", message);
    }
    public void sendImageMessage(String from,String toUser, String base64Image) {
        sendMessage(from,"image", toUser, base64Image);
    }
    private void sendMessage(String  From ,String toUser,String type,  String content) {
        try {
            JSONObject json = new JSONObject();
            json.put("from",From);
            json.put("type", type);
            json.put("to", toUser);
            json.put("content", content);
            
            if (webSocket != null && webSocket.isOpen()) {
                webSocket.send(json.toString());
            }
        } catch (JSONException e) {
            Log.e(TAG, "Create message error: " + e.getMessage());
        }
    }
    public void disconnect() {
        if (webSocket != null) {
            webSocket.close();
        }
    }
    private SSLContext createInsecureSSLContext() throws Exception {
        @SuppressLint("CustomX509TrustManager") TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
            @SuppressLint("TrustAllX509TrustManager")
            public void checkClientTrusted(X509Certificate[] certs, String authType) {}
            @SuppressLint("TrustAllX509TrustManager")
            public void checkServerTrusted(X509Certificate[] certs, String authType) {}
        }};
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, new SecureRandom());
        return sslContext;
    }
}